package com.ideal.tools.ssh.operation.hdfs;

import com.ideal.tools.ssh.common.CommonProperties;
import com.ideal.tools.ssh.common.CommonTools;
import com.ideal.tools.ssh.context.ClusterContext;
import com.ideal.tools.ssh.entity.LinuxCommand;
import com.ideal.tools.ssh.operation.LinuxOperation;
import com.ideal.tools.ssh.result.LinuxResult;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by CC on 2016/3/14.
 */
public class QuotaHDFS extends LinuxOperation {

    String superUser;
    String userName;
    String spaceSzie;
    String dirNumber;
    String dir;


    public QuotaHDFS(String userName, String spaceSzie, String dirNumber) {
        this.userName = userName;
        this.spaceSzie = spaceSzie;
        this.dirNumber = dirNumber;
    }

    @Override
    public void execLinuxCMD(ClusterContext context) {
        this.superUser = context.getCommonProperties().getProperty(CommonProperties.HDFS_SUPER_USER, "hdfs");
        this.dir = CommonTools.getHDFSParentDir(userName, context.getCommonProperties());

        //具体去运行的命令  这个地方 可能不灵活 如果需要修改命令 会需要修改代码
        //这里后面可以移动到从数据库中载入数据
        //如果为空 则 清空
        String cmd = "";
        if (!StringUtils.isBlank(spaceSzie)) {
            cmd = cmd + "sudo -u " + superUser + " hadoop dfsadmin -setSpaceQuota " + spaceSzie + " " + dir;
        }else{
            cmd = cmd + "sudo -u " + superUser + " hadoop dfsadmin -clrSpaceQuota " + dir;
        }
        if (!StringUtils.isBlank(cmd)) {
            cmd = cmd + ";";
        }
        if (!StringUtils.isBlank(dirNumber)) {
            cmd = cmd + "sudo -u " + superUser + " hadoop dfsadmin -setQuota " + dirNumber + " " + dir;
        }else{
            cmd = cmd + "sudo -u " + superUser + " hadoop dfsadmin -clrQuato " +dir;
        }

        //创建命令 创建命令的时候 需要根据不同的OperationType 初始化不同的参数
        setLinuxCommand(new LinuxCommand().initCMD(cmd));

        /**这个分割线是为了说明下面的是基本不用变的，如果要实现新的功能，只需要写上面**/

        //执行
        super.execOperation(context);
    }

    @Override
    public void setResultNote(LinuxResult linuxResult) {
//        String info = getResultInfo();
        int exitcode = linuxResult.getExitCode();
        String exitCodeMean = "";
        String host = getHost();
        if (exitcode == 0) {
            exitCodeMean = "SUCCESS QUOTA HDFS DIR ! [" + dir + "] SapceSize[" + spaceSzie + "] DirNumber[" + dirNumber + "] [" + host + "]\n";
        } else {
            exitCodeMean = "FAILD QUOTA HDFS DIR ! [" + dir + "] SapceSize[" + spaceSzie + "] DirNumber[" + dirNumber + "] [" + host + "]\n";
        }
        //设置note
        linuxResult.setNote(exitCodeMean+(StringUtils.isBlank(linuxResult.getNote())?"":linuxResult.getNote()));
    }

}
